package biz

import (
	"server/base/db"
	"server/biz/proto"
)

type PkgRaw struct {
	Id        int     `json:"id"`
	VersionId int     `json:"version_id"`
	GameId    int     `json:"game_id"`
	Name      string  `json:"name"`
	Size      float64 `json:"size"`
	Src       string  `json:"src"`
	BindId    int     `json:"bind_id"`
}

func GetPackage(id int) *PkgRaw {
	if id == 0 {
		return nil
	}
	var o = &PkgRaw{}
	ok := db.Replica.QueryRowx(`select version_id, game_id, name, sizea, src, bind_id from package where id=?`, id).Scan(
		&o.VersionId, &o.GameId, &o.Name, &o.Size, &o.Src, &o.BindId)
	if !ok {
		return nil
	}
	o.Id = id
	return o
}

type OrderPkgRaw struct {
	Id      int     `json:"id"`
	OrderId int     `json:"order_id"`
	PkgId   int     `json:"pkg_id"`
	PkgSize float64 `json:"pkg_size"`
	PkgSrc  string  `json:"pkg_src"`
	Status  int     `json:"status"`
}

// 返回第一个未完成的任务
func PopOrderPkg(order_id int) *OrderPkgRaw {
	if order_id == 0 {
		return nil
	}
	var o = &OrderPkgRaw{}
	ok := db.Replica.QueryRowx(`select id, pkg_id, pkg_size, pkg_src, status from order_pkg 
where status=0 and order_id=? limit 1`, order_id).Scan(
		&o.Id, &o.PkgId, &o.PkgSize, &o.PkgSrc, &o.Status)
	if !ok {
		return nil
	}
	o.OrderId = order_id
	return o
}

func GetOrderPkg(id int) *OrderPkgRaw {
	if id == 0 {
		return nil
	}
	var o = &OrderPkgRaw{}
	ok := db.Replica.QueryRowx(`select order_id, pkg_id, pkg_size, pkg_src, status from order_pkg where id=? limit 1`, id).Scan(
		&o.OrderId, &o.PkgId, &o.PkgSize, &o.PkgSrc, &o.Status)
	if !ok {
		return nil
	}
	o.Id = id
	return o
}

func SetOrderPkgStatus(id, status int) {
	db.Primary.Exec(`update order_pkg set status=? where id=?`, status, id)
}

func GetWaitingPkgs() []*proto.WaitingPkg {
	out := []*proto.WaitingPkg{}
	rows := db.Replica.Query(`select p.id, o.no, p.src from orders o
inner join order_pkg op on op.order_id=o.id
inner join package p on p.id=op.pkg_id
where o.status in (1,2,3) order by o.id
group by p.id`)
	defer rows.Close()
	for rows.Next() {
		var r = &proto.WaitingPkg{}
		rows.Scan(&r.PkgId, &r.OrderNo, &r.Src)
		out = append(out, r)
	}
	return out
}
